<template>
  <view>
    <scroll-view
      :scroll-y="modalName == null"
      class="page"
      :class="modalName != null ? 'show' : ''"
    >
      <cu-custom class="custom-nav">
        <block slot="left">
          <view @tap="goback">
            <text>返回</text>
          </view>
        </block>
        <block slot="content">XX轨迹详情</block>
        <block slot="right">
          <view @tap="changeStatus" data-target="DialogModal1">
            <text>修改状态</text>
          </view>
        </block>
      </cu-custom>
      <!-- 轨迹回放 -->
      <view id="container" class="container"></view>
      <!-- 事件处理弹窗 -->
      <view class="cu-modal" :class="modalName == 'DialogModal1' ? 'show' : ''">
        <view class="cu-dialog">
          <view class="cu-bar bg-title justify-end">
            <view class="content">提示</view>
            <view class="action" @tap="hideModal">
              <text
                class="cuIcon-close text-white"
                style="font-weight: 700"
              ></text>
            </view>
          </view>
          <view class="padding-xl">
            <!-- Modal 内容。 -->
            <text>将此事件设置为</text
            ><text style="font-size: 18px; font-weight: 700"
              >【{{ status == 0 ? "已确认" : "待确认" }}】</text
            >状态
          </view>
          <view class="cu-bar bg-white justify-center">
            <view class="action">
              <button class="cu-btn bg-red" @tap="hideModal">取消</button>
              <button class="cu-btn bg-blue margin-left" @tap="hideModal">
                确定
              </button>
            </view>
          </view>
        </view>
      </view>
      <!-- 事件列表弹窗 -->
      <view
        class="cu-modal bottom-modal"
        :class="modalName == 'bottomModal' ? 'show' : ''"
      >
        <view class="cu-dialog">
          <view class="cu-bar bg-title">
            <view class="action text-white">目标ID:1232131</view>

            <view class="action text-blue">
              <text
                @tap="hideModal"
                class="cuIcon-close text-white"
                style="font-weight: 700"
              ></text>
            </view>
          </view>
          <view class="content_bottom">
            <text class="text-black c-item"
              >目标名称: <text class="text-grey">12</text></text
            >

            <text class="text-black c-item"
              >所属区域: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >检测类型: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >目标类型: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >频段: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >距离: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >方位: <text class="text-grey">12</text></text
            >

            <text class="text-black c-item"
              >经度: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >纬度: <text class="text-grey">12</text></text
            >

            <text class="text-black c-item"
              >幅度: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >速度: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >日期: <text class="text-grey">12</text></text
            >
            <text class="text-black c-item"
              >时间: <text class="text-grey">12</text></text
            >
            <button
              class="cu-btn bg-blue por20 animation-slide-top"
              @tap="handleNavigation"
            >
              导航
            </button>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: "track1",
  data() {
    return {
      modalName: null,
      status: 0,
      map: null,
      path: [],
      // 目标纬度
      latitude: "",
      // 目标经度
      longitude: "",
      // 目标地址名称
      name: "",
      // 目标地址详细信息
      address: "",
      // 我自己的位置经纬度（百度地图需要传入自己的经纬度进行导航）
      selfLocation: {
        latitude: "",
        longitude: "",
      },
    };
  },
  created() {
    console.log(this.$Router.getPageRoute(), "$Router");
    this.status = this.$Router.getPageRoute().query.status;
  },
  mounted() {
    const A_MAP_KEY = "cd60afb4e5a22c569f4c42ce75a34be5"; // 地图key
    const A_MAP_SECRET_KEY = "8c30043dbe2ac5dbcedaa5f2e7320d48"; // 地图密钥
    // 地图初始化
    // if (typeof window.AMap === 'function') {
    // 		this.initAmap();
    // 	} else {
    window._AMapSecurityConfig = {
      securityJsCode: A_MAP_SECRET_KEY,
    };
    // const script = document.createElement("script");
    // script.src = `https://webapi.amap.com/maps?v=1.4.15&key=${A_MAP_KEY}&plugin=AMap.Walking`;
    // script.onload = this.initAmap.bind(this);
    // document.head.appendChild(script);
    // }
  },
  methods: {
    goback() {
      // this.$Router.push({ name: "event" });
      uni.navigateBack({
        delta: 1,
      });
    },
    //初始化地图
    initAmap() {
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        center: [116.397155, 39.916345],
        zoom: 12,
      });
      AMap.plugin(["AMap.ToolBar", "AMap.Scale"]);
      //添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
      this.map.addControl(new AMap.ToolBar());

      //添加比例尺控件，展示地图在当前层级和纬度下的比例尺
      this.map.addControl(new AMap.Scale());
      this.manyPersonWays();
    },
    // 修改状态
    changeStatus(e) {
      this.modalName = e.currentTarget.dataset.target;
    },
    hideModal() {
      this.modalName = null;
    },
    //多目标点实时封装
    manyPersonWays() {
      const _this = this;
      // 北京主城区的经纬度范围
      const minLatitude = 39.442; // 最小纬度
      const maxLatitude = 39.864; // 最大纬度
      const minLongitude = 116.172; // 最小经度
      const maxLongitude = 116.553; // 最大经度
      // 定义生成标记点的数量
      // const numMarkers = 2;
      const numMarkers = [
        {
          id: 1,
          url: "../static/avatar_girl.png", // 图标的URL地址
        },
      ];
      // 定义更新标记点位置的时间间隔（毫秒）
      const updateInterval = 1000;
      // 生成标记点
      const markers = [];
      for (let i = 0; i < numMarkers.length; i++) {
        // 随机生成初始经纬度
        const latitude =
          Math.random() * (maxLatitude - minLatitude) + minLatitude;
        const longitude =
          Math.random() * (maxLongitude - minLongitude) + minLongitude;
        // 随机选择一个图标
        const marker = new AMap.Marker({
          id: numMarkers[i].id,
          position: [latitude, longitude],
          // icon: numMarkers[i].url,
          offset: new AMap.Pixel(-10, -30),
          map: _this.map,
        });

        // 将标记点添加到数组中
        markers.push(marker);
      }

      // 定时器更新标记点位置
      const updateMarkerPositions = setInterval(() => {
        // 模拟更新标记点位置 轨迹回放可以使用此方法
        // 创建标记点对象
        function createMarker(longitude, latitude) {
          const marker = new AMap.Marker({
            position: [longitude, latitude],
            // icon: numMarkers[i].url,
            offset: new AMap.Pixel(-10, -30),
            map: _this.map,
            // iconSize: new AMap.Size(30, 30),
          });
          return marker;
        }
        // 绘制行驶路径
        function drawPath(path) {
          _this.path.push(path);
          // 将路径添加到对应标记点的路径数组中
          // 创建 Polyline 对象
          var index = 5;
          // 遍历标记点数组，更新每个标记点的位置
          // 创建 Polyline 对象
          var routeLine = new AMap.Polyline({
            path: _this.path, // 将所有路径数组拼接为一个路径数组
            showDir: true,
            isOutline: true,
            outlineColor: "#ffeeee",
            borderWeight: 2,
            strokeColor: "#fd3e4a", // 使用不同的深色区分不同的轨迹
            strokeWeight: 6,
            lineJoin: "round",
            lineCap: "round",
          });
          index++;
          // 将 Polyline 对象添加到地图上
          _this.map.add(routeLine);
        }
        // 添加标记点，并开始绘制行驶路径
        function addMarkerAndDrawPath(position) {
          console.log(position, "position");
          drawPath([position.lng, position.lat]);
          // 创建新的标记点
          const marker = createMarker(position.lng, position.lat);
          // 添加地图点击事件监听器
          _this.map.on("click", function (e) {
            console.log("Map clicked!");
          });

          // 添加标记点点击事件监听器
          marker.on("click", function (e) {
            _this.modalName = "bottomModal";
            console.log("Marker clicked!", e);
          });
          _this.map.add(marker);
          // 将标记点位置添加到路径中
        }
        // 存储每个标记点的路径
        markers.forEach((marker) => {
          // 随机生成新的经纬度
          const newLatitude =
            Math.random() * (maxLatitude - minLatitude) + minLatitude;
          const newLongitude =
            Math.random() * (maxLongitude - minLongitude) + minLongitude;
          // 更新标记点位置
          marker.setPosition([newLongitude, newLatitude]);
          // 获取标记点的经纬度
          const position = marker.getPosition();
          // 绘制该标记点的路径
          // drawPath(position);
          addMarkerAndDrawPath(position);
        });
      }, updateInterval);

      // 模拟一段时间后停止更新（这里使用伪代码代替）
      setTimeout(() => {
        clearInterval(updateMarkerPositions);
        console.log("更新已停止");
        // 示例：更新已停止，移除对应标记点和路径
        // _this.map.remove(
        //   _this.map.getAllOverlays("marker")[
        //     _this.map.getAllOverlays("marker").length - 1
        //   ]
        // );
      }, 10000); // 模拟更新持续5秒钟
    },
    handleNavigation() {
      const _this = this;
      if (!this.latitude || !this.longitude || !this.name) return;
      // 微信
      // #ifdef MP-WEIXIN
      let _obj = {
        latitude: parseFloat(this.latitude),
        longitude: parseFloat(this.longitude),
        name: this.name,
      };
      if (this.address) {
        _obj["address"] = this.address;
      }
      uni.openLocation({
        ..._obj,
        success: function (res) {
          console.log("打开系统位置地图成功");
        },
        fail: function (error) {
          console.log(error);
        },
      });
      // #endif

      // #ifdef APP-PLUS
      // 判断系统安装的地图应用有哪些, 并生成菜单按钮
      let _mapName = [
        {
          title: "高德地图",
          name: "amap",
          androidName: "com.autonavi.minimap",
          iosName: "iosamap://",
        },
        {
          title: "百度地图",
          name: "baidumap",
          androidName: "com.baidu.BaiduMap",
          iosName: "baidumap://",
        },
        {
          title: "腾讯地图",
          name: "qqmap",
          androidName: "com.tencent.map",
          iosName: "qqmap://",
        },
      ];
      // 根据真机有的地图软件 生成的 操作菜单
      let buttons = [];
      let platform = uni.getSystemInfoSync().platform;
      platform === "android" &&
        _mapName.forEach((item) => {
          if (plus.runtime.isApplicationExist({ pname: item.androidName })) {
            buttons.push(item);
          }
        });
      platform === "ios" &&
        _mapName.forEach((item) => {
          console.log(item.iosName);
          if (plus.runtime.isApplicationExist({ action: item.iosName })) {
            buttons.push(item);
          }
        });
      if (buttons.length) {
        plus.nativeUI.actionSheet(
          {
            //选择菜单
            title: "选择地图应用",
            cancel: "取消",
            buttons: buttons,
          },
          function (e) {
            let _map = buttons[e.index - 1];
            _this.openURL(_map, platform);
          }
        );
      } else {
        uni.showToast({
          title: "请安装地图软件",
          icon: "none",
        });
        return;
      }
      // #endif
    },

    // 打开第三方程序实际应用
    openURL(map, platform) {
      let _defaultUrl = {
        android: {
          amap: `amapuri://route/plan/?sid=&did=&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          qqmap: `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          baidumap: `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo"`,
        },
        ios: {
          amap: `iosamap://path?sourceApplication=fuxishan_uni_client&dlat=${this.latitude}&dlon=${this.longitude}&dname=${this.name}&dev=0&t=0`,
          qqmap: `qqmap://map/routeplan?type=drive&to=${this.name}&tocoord=${this.latitude},${this.longitude}&referer=fuxishan_uni_client`,
          baidumap: `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=name:${this.name}|latlng:${this.latitude},${this.longitude}&mode=driving&src=ios.baidu.openAPIdemo`,
        },
      };
      let newurl = encodeURI(_defaultUrl[platform][map.name]);
      console.log(newurl);
      plus.runtime.openURL(
        newurl,
        function (res) {
          console.log(res);
          uni.showModal({
            content: res.message,
          });
        },
        map.androidName ? map.androidName : ""
      );
    },
  },
};
</script>

<style scoped>
.page {
  height: 100vh;
  width: 100vw;
}

.page.show {
  overflow: hidden;
}
.custom-nav,
.cu-bar.fixed {
  color: aliceblue;
}
.cu-item {
  background-color: #fff;
  margin-bottom: 10px;
  border-radius: 5px;
}
#container {
  height: 100vh;
  width: 100vw;
}
::v-deep .amap-touch-toolbar .amap-zoomcontrol {
  position: absolute;
  bottom: 20px !important;
}
.content_bottom {
  display: flex;
  flex-wrap: wrap;
  padding: 15px;
}
.cu-list {
  margin: 10px 17px;
}
.c-item {
  width: 45%;
  padding: 5px 0;
  /* margin: 5px 0; */
  text-align: left;
}
.cu-item1 {
  position: relative;
}
.cu-tag1 {
  position: absolute;
  top: 2px;
  left: 0;
}
.ml15 {
  margin-left: 35px;
}
.por20 {
  position: absolute;
  right: 20px;
  top: 70px;
}
</style>
